package com.main.mainpro.system.service;

import com.main.mainpro.db.datasource.DataSource;
import com.main.mainpro.db.datasource.DataSourceNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Service
public class SystemService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @DataSource
    public String getDBtest() {
        List<Map<String, Object>> res = jdbcTemplate.queryForList("SELECT * FROM sys_user");
        return res.toString();
    }

    @DataSource(DataSourceNames.TWO)
    public String getDBtest2() {
        List<Map<String, Object>> res = jdbcTemplate.queryForList("SELECT * FROM xxl_sso_user");
        return res.toString();
    }

    @DataSource
    public String getFileFromDB() {
        List<Map<String, Object>> res = jdbcTemplate.queryForList("SELECT * FROM sys_user");
        return res.toString();
    }

    /**
     * 查询数据库中的jar包
     * @return list
     */
    @DataSource
    public List<Map<String, Object>> uploadJar() {
        List<Map<String, Object>> resObject = new ArrayList<Map<String, Object>>();
        String sql = "SELECT ID, MODULE, MODULE_NAME, JAR, LOADTIME, UPDTIME FROM sys_hd_jars";
        final LobHandler lobHandler = new DefaultLobHandler();
        List<Map<String,String>> list = jdbcTemplate.query(sql, new RowMapper(){
            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException
            {
                //以二进制的数组方式获得Blob数据,第二个参数3是指blob字段在结果集的位置
                InputStream attach = lobHandler.getBlobAsBinaryStream(rs, 4);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("ID", rs.getString("ID"));
                map.put("MODULE", rs.getString("MODULE"));
                map.put("MODULE_NAME", rs.getString("MODULE_NAME"));
                map.put("JAR", attach);
                map.put("LOADTIME", rs.getString("LOADTIME"));
                map.put("UPDTIME", rs.getString("UPDTIME"));
                resObject.add(map);
                return map;
            }
        });
        return resObject;
    }

    /**
     * 获取jar包
     * @param datas
     * @param request
     * @return
     */
    public File getFileByDbJars(List<Map<String, Object>> datas, HttpServletRequest request) throws FileNotFoundException {
        InputStream attach = (InputStream) uploadJar().get(0).get("JAR");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        File jarFile = new File(path);
        return jarFile;
    }

    /**
     * 保存文件
     * @param file
     */
    @DataSource
    public void saveFile(MultipartFile file) throws IOException {
        //文件流
        InputStream fileInputStream = file.getInputStream();
        //文件后缀
        String filename = file.getOriginalFilename();
        LobHandler lobHandler = new DefaultLobHandler();
        jdbcTemplate.execute( " INSERT INTO sys_hd_jars (ID, MODULE, MODULE_NAME, JAR) VALUES (?, ?, ?, ?) ",
            new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
                @Override
                protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                    try {
                        ps.setString(1, String.valueOf(UUID.randomUUID()));
                        ps.setString(2, filename);
                        ps.setString(3, filename);
                        lobCreator.setBlobAsBinaryStream(ps, 4, fileInputStream, file.getBytes().length);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        );
    }


}
